package com.talkweb.reader.maintab.detail;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.talkweb.baselibrary.base.BaseAbilitySlice;
import com.talkweb.baselibrary.utils.LogUtil;
import com.talkweb.baselibrary.utils.PreferencesUtils;
import com.talkweb.reader.ResourceTable;
import com.talkweb.reader.bookshelf.bean.BookBean;
import com.talkweb.reader.maintab.TestSlice;
import com.talkweb.reader.maintab.bean.CollBookBean;
import com.talkweb.reader.maintab.bean.SearchBookBean;
import com.zhouyou.http.EasyHttp;
import com.zhouyou.http.callback.SimpleCallBack;
import com.zhouyou.http.exception.ApiException;
import com.zhouyou.http.model.HttpHeaders;
import com.zhouyou.http.ohos.MainThreadDisposable;
import com.zhouyou.http.utils.TextUtils;
import io.reactivex.rxjava3.core.Observable;
import io.reactivex.rxjava3.core.ObservableEmitter;
import io.reactivex.rxjava3.core.ObservableOnSubscribe;
import io.reactivex.rxjava3.schedulers.Schedulers;
import ohos.aafwk.content.Intent;
import ohos.agp.animation.AnimatorProperty;
import ohos.agp.components.Component;
import ohos.agp.components.Image;
import ohos.agp.components.Text;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.nodes.TextNode;

import java.util.ArrayList;
import java.util.List;

public class BookDetailAbilitySlice extends BaseAbilitySlice {

    private Image iv_blur_cover;
    private Image iv_cover;
    private Text tv_name;
    private Text tv_author;
    private Text tv_origin;
    private Text tv_chapter;
    private Text tv_intro;
    private Text tv_shelf;
    private Text tv_read;
    private Text tv_loading;
    private SearchBookBean searchBookBean;

    @Override
    protected int getLayoutId() {
        return ResourceTable.Layout_ability_book_detail;
    }

    @Override
    protected void initComponent() {
        Intent intent = getIntent();
        if(intent != null){
            searchBookBean = intent.getSerializableParam("searchBookBean");
        }
        iv_blur_cover = findById(ResourceTable.Id_iv_blur_cover);
        iv_cover = findById(ResourceTable.Id_iv_cover);
        tv_name = findById(ResourceTable.Id_tv_name);
        tv_author = findById(ResourceTable.Id_tv_author);
        tv_origin = findById(ResourceTable.Id_tv_origin);
        tv_chapter = findById(ResourceTable.Id_tv_chapter);
        tv_intro = findById(ResourceTable.Id_tv_intro);
        tv_shelf = findById(ResourceTable.Id_tv_shelf);
        tv_read = findById(ResourceTable.Id_tv_read);
        tv_loading = findById(ResourceTable.Id_tv_loading);

        AnimatorProperty animatorProperty = tv_loading.createAnimatorProperty();
        animatorProperty.setDuration(2000).setLoopedCount(Integer.MAX_VALUE)
                .setDelay(500).rotate(360).start();
        animatorProperty.setTarget(tv_loading);

        tv_loading.setBindStateChangedListener(new Component.BindStateChangedListener() {
            @Override
            public void onComponentBoundToWindow(Component component) {
                if (animatorProperty != null) {
                    animatorProperty.start();
                }
            }

            @Override
            public void onComponentUnboundFromWindow(Component component) {

            }
        });

        String coverUrl = searchBookBean.getCoverUrl();
        String name = searchBookBean.getName();
        String author = searchBookBean.getAuthor();
        if (searchBookBean.getOrigin() != null && searchBookBean.getOrigin().length() > 0) {
            tv_origin.setVisibility(Component.VISIBLE);
            String sourceWebsit = "来源:" + searchBookBean.getOrigin();
            tv_origin.setText(sourceWebsit);
        } else {
            tv_origin.setVisibility(Component.HIDE);
        }
        Glide.with(getContext())
                .load(coverUrl)
                .diskCacheStrategy(DiskCacheStrategy.NONE)
                .skipMemoryCache(true)
                .into(iv_cover);

        Glide.with(getContext())
                .load(coverUrl)
                .diskCacheStrategy(DiskCacheStrategy.NONE)
                .skipMemoryCache(true)
                .into(iv_blur_cover);
        tv_name.setText(name);
        tv_author.setText(author);

        tv_read.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                present(new TestSlice(), new Intent());
            }
        });
        tv_shelf.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                String favData = PreferencesUtils.getInstance(getAbility()).getString("DATA_FAV_BOOK","");
                Gson gson = new Gson();
                List<BookBean> bookDatas;
                if(!TextUtils.isEmpty(favData)){
                    bookDatas = gson.fromJson(favData, new TypeToken<List<BookBean>>(){}.getType());
                }else{
                    bookDatas = new ArrayList<>();
                }
                bookDatas.add(0,searchBookBean.toBookBean());
                String favResultData = gson.toJson(bookDatas,new TypeToken<List<BookBean>>(){}.getType());
                PreferencesUtils.getInstance(getAbility()).putToPreferences("DATA_FAV_BOOK",favResultData);
            }
        });
    }

    @Override
    protected void getData() {
        String url1 = "https://www.9txs.com";
        String url2 = "https://www.wxguan.com";
        String url3 = "http://www.wzzw.la";
        String url4 = "https://www.yb3.cc";
        CollBookBean collBookInfo = new CollBookBean().getCollBookBeanFromSearch(searchBookBean);
        String baseUrl = "";
        if(collBookInfo.getBookTag().equals(url1)){
            baseUrl = url1;
        }else if(collBookInfo.getBookTag().equals(url2)){
            baseUrl = url2;
        }else if(collBookInfo.getBookTag().equals(url3)){
            baseUrl = url3;
        }else if(collBookInfo.getBookTag().equals(url4)){
            baseUrl = url4;
        }

        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.put("Accept","text/html,application/xhtml+xml,application/xml");
        httpHeaders.put("User-Agent","Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.9.0.3) Gecko/2008092417 Firefox/3.0.3");
        httpHeaders.put("Accept-Charset","UTF-8");
        httpHeaders.put("Connection","close");
        httpHeaders.put("Cache-Control","no-cache");

        EasyHttp.get(collBookInfo.get_id().replace(baseUrl, ""))
                .baseUrl(baseUrl)
                .headers(httpHeaders)
                .readTimeOut(30 * 1000)//局部定义读超时
                .writeTimeOut(30 * 1000)
                .connectTimeout(30 * 1000)
                .timeStamp(true)
                .execute(new SimpleCallBack<String>() {
                    @Override
                    public void onError(ApiException e) {
                        LogUtil.e("data===",e.getMessage());

                    }

                    @Override
                    public void onSuccess(String response) {
                        if (response != null) {
                            LogUtil.e("data===",response);
//                            analyBookInfo(response,collBookInfo);
                        }
                    }
                });
    }

    private CollBookBean analyBookInfo(final String s, final CollBookBean collBookBean) {

        collBookBean.setBookTag(collBookBean.getBookTag());
        Document doc = Jsoup.parse(s);
        Element resultE = doc.getElementsByClass("book").get(0);

        collBookBean.setCover(collBookBean.getBookTag() + resultE.getElementsByTag("img").get(0).attr("src"));

        collBookBean.setTitle(resultE.getElementsByTag("img").get(0).attr("alt"));
        String author = resultE.getElementsByClass("small").get(0).getElementsByTag("span").get(0).text().toString().trim();
        author = author.replace(" ", "").replace("  ", "").replace("作者：", "");
        collBookBean.setAuthor(author);
        String updatedTime = resultE.getElementsByClass("small").get(0).getElementsByTag("span").get(4).text().toString().trim();
        updatedTime = updatedTime.replace(" ", "").replace("  ", "").replace("更新时间：", "");

        collBookBean.setUpdated(updatedTime);

        collBookBean.setLastChapter(resultE.getElementsByClass("small").get(0).getElementsByTag("span").get(5).text().toString().trim());
        List<TextNode> contentEs = resultE.getElementsByClass("intro").get(0).textNodes();
        StringBuilder content = new StringBuilder();
        for (int i = 0; i < contentEs.size(); i++) {
            String temp = contentEs.get(i).text().trim();
            temp = temp.replaceAll(" ", "").replaceAll(" ", "");
            if (temp.length() > 0) {
                content.append("\u3000\u3000" + temp);
                if (i < contentEs.size() - 1) {
                    content.append("\r\n");
                }
            }
        }

        collBookBean.setShortIntro(content.toString());
        collBookBean.setBookChapterUrl(collBookBean.get_id());
        try {
            String kind = resultE.getElementsByClass("small").get(0).getElementsByTag("span").get(1).text().replace("分类：", "");
            String lastChapter = resultE.getElementsByClass("small").get(0).getElementsByTag("span").get(5).getElementsByTag("a").text();
//                    ObtainBookInfoImpl.getInstance().senMessageManpin(collBookBean, kind, lastChapter);
        } catch (Exception e1) {
            e1.printStackTrace();
        }

        return collBookBean;
    }

    private void updateView(CollBookBean collBookBean){

    }

}
